package com.dhh.web.common.init;

import com.dhh.web.common.shiro.ShiroUtils;
import com.dhh.web.common.utils.RandomUtil;
import com.dhh.web.modules.menu.domain.Menu;
import com.dhh.web.modules.user.domain.Perms;
import com.dhh.web.modules.user.domain.Role;
import com.dhh.web.modules.user.domain.User;
import com.dhh.web.modules.menu.repo.MenuRepo;
import com.dhh.web.modules.user.repo.PermsRepo;
import com.dhh.web.modules.user.repo.RoleRepo;
import com.dhh.web.modules.user.repo.UserRepo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static com.dhh.web.common.utils.Constant.SUPER_ADMIN_ID;
import static com.dhh.web.common.utils.UserConst.*;

/**
 * @Auther: dhh
 * @Date: 2018/11/22 16:17
 * @Email: fzlinjianhui@163.com
 * @Description: 启动程序后后执行
 */
@Component//被spring容器管理
@Order(1)//如果多个自定义ApplicationRunner，用来标明执行顺序
@Slf4j
public class InitData implements CommandLineRunner {

    @Autowired
    private UserRepo userRepo;
    @Autowired
    private RoleRepo roleRepo;
    @Autowired
    private PermsRepo permsRepo;
    @Autowired
    private MenuRepo menuRepo;

    private void initUser(){
        //权限
        Perms user_save = Perms.builder().permId(RandomUtil.randomUUID()).name(USER_SAVE).build();
        Perms user_update = Perms.builder().permId(RandomUtil.randomUUID()).name(USER_UPDATE).build();
        Perms user_delete = Perms.builder().permId(RandomUtil.randomUUID()).name(USER_DELETE).build();
        Perms user_list = Perms.builder().permId(RandomUtil.randomUUID()).name(USER_LIST).build();
        Perms index_console = Perms.builder().permId(RandomUtil.randomUUID()).name(INDEX_CONSOLE).build();
        Perms system_index = Perms.builder().permId(RandomUtil.randomUUID()).name(SYSTEM_INDEX).build();
        Perms system_menu_list = Perms.builder().permId(RandomUtil.randomUUID()).name(SYSTEM_MENU_LIST).build();
        Perms system_menu_save = Perms.builder().permId(RandomUtil.randomUUID()).name(SYSTEM_MENU_SAVE).build();
        Perms system_menu_delete = Perms.builder().permId(RandomUtil.randomUUID()).name(SYSTEM_MENU_DELETE).build();
        Perms system_user_list = Perms.builder().permId(RandomUtil.randomUUID()).name(SYSTEM_USER_LIST).build();
        Perms system_role_list = Perms.builder().permId(RandomUtil.randomUUID()).name(SYSTEM_ROLE_LIST).build();
        Perms system_perms_list = Perms.builder().permId(RandomUtil.randomUUID()).name(SYSTEM_PERMS_LIST).build();
        List<Perms> permsList = new ArrayList<Perms>(){{
            add(user_save);
            add(user_update);
            add(user_delete);
            add(user_list);
            add(index_console);
            add(system_index);
            add(system_menu_list);
            add(system_menu_save);
            add(system_user_list);
            add(system_role_list);
            add(system_perms_list);
            add(system_menu_delete);
        }};
        permsRepo.saveAll(permsList);
        //角色
        Set<Perms> permsSet = new HashSet<>(permsList);
        Role superAdmin = Role.builder().roleId(RandomUtil.randomUUID()).roleCode(SUPER_ADMIN).name("超级管理员").perms(permsSet).build();
        Role normalUser = Role.builder().roleId(RandomUtil.randomUUID()).roleCode(NORMAL_USER).name("普通用户").build();
        Role normalAdmin = Role.builder().roleId(RandomUtil.randomUUID()).roleCode(NORMAL_ADMIN).name("普通管理员").build();
        List<Role> roleList = new ArrayList<Role>(){{
            add(superAdmin);
            add(normalUser);
            add(normalAdmin);
        }};
        roleRepo.saveAll(roleList);
        //用户
        Set<Role> roleSet = new HashSet<>();
        roleSet.add(superAdmin);
        String salt = RandomStringUtils.randomAlphanumeric(20);
        String password = ShiroUtils.sha256("admin", salt);
        User user = User.builder()
                .userId(SUPER_ADMIN_ID)
                .status(1)
                .roles(roleSet)
                .username("超级管理员")
                .password(password)
                .salt(salt)
                .build();
        userRepo.save(user);
    }

    private void initMenu(){
        //----------------------------控制台-------------------------------------
        Set<Perms> index_console = permsRepo.findAllByNameIn(new ArrayList<String>(){{add(INDEX_CONSOLE);}});
        Menu console = _generateMenu("控制台", index_console, "0", "pages/home/console.html","layui-icon-home",0);
        //----------------------------系统管理菜单-------------------------------
        Set<Perms> system_index = permsRepo.findAllByNameIn(new ArrayList<String>(){{add(SYSTEM_INDEX);}});
        Menu systemManager = _generateMenu("系统管理", system_index, "0", "pages/system/index.html","layui-icon-app",0);
        String systemManagerMenuId = systemManager.getMenuId();
        //菜单管理菜单
        Set<Perms> system_menu = permsRepo.findAllByNameIn(new ArrayList<String>(){{add(SYSTEM_MENU_LIST);}});
        Menu menuManager = _generateMenu("菜单管理", system_menu, systemManagerMenuId,"pages/system/menu.html","layui-icon-set", 1);
        //权限管理菜单
        Set<Perms> system_perms_list = permsRepo.findAllByNameIn(new ArrayList<String>(){{add(SYSTEM_PERMS_LIST);}});
        Menu permsManager = _generateMenu("权限管理", system_perms_list, systemManagerMenuId,"pages/system/perms.html","layui-icon-set", 2);
        //角色管理菜单
        Set<Perms> system_role_list = permsRepo.findAllByNameIn(new ArrayList<String>(){{add(SYSTEM_ROLE_LIST);}});
        Menu roleManager = _generateMenu("角色管理", system_role_list, systemManagerMenuId,"pages/system/role.html","layui-icon-set", 2);
        //用户管理菜单
        Set<Perms> system_user_list = permsRepo.findAllByNameIn(new ArrayList<String>(){{add(SYSTEM_USER_LIST);}});
        Menu userManager = _generateMenu("用户管理", system_user_list, systemManagerMenuId,"system/user.html","layui-icon-set", 2);
        Menu test = _generateMenu("test", null, userManager.getMenuId(),"pages/system/user.html","layui-icon-set", 2);

        //------------------------------------------------------------------------
        List<Menu> menuList = new ArrayList<Menu>(){{add(console);add(systemManager);add(menuManager);add(permsManager);add(roleManager);add(userManager);add(test);}};
        menuRepo.saveAll(menuList);
    }

    private Menu _generateMenu(String name,Set<Perms> permsSet,String pid,String url,String icon,int orderNum){
        return Menu.builder()
                .menuId(RandomUtil.randomUUID())
                .pid(pid)
                .icon(icon)
                .name(name)
                .orderNum(orderNum)
                .type(Menu.MENU)
                .url(url)
                .perms(permsSet)
                .build();
    }

    @Override
    public void run(String... args) {
        log.info("项目启动成功，时间：{}", LocalDateTime.now().toString());
        if(!userRepo.findByUsername("超级管理员").isPresent()){
            //如果“超级管理员”用户存在，就不再进行初始化数据
            initUser();
            log.info("内置用户数据初始化成功");

        }
        if(menuRepo.findAll().size() == 0){
            initMenu();
            log.info("初始菜单数据初始化成功");
        }

    }
}
